import React, { Fragment } from 'react'
import './index.less'
import SubTitle from '../components/SubTitle';
import http from 'libs/http';
import { HelpCenter } from 'components'
import _ from 'lodash'
import { getPlatformType } from 'libs/utils'

export default class StudentCenterHome extends React.Component {
  state = {
    currCalendar: [],
    nextCalendar: [],
    challengeTimes: 0, //累计挑战次数
    englishStudyHours: 0, //累计英语学习时间
    programStudyHours: 0, //累计编程学习时间
    trainTimes: 0, //累计练习次数
    isContainChallenge: false,
    level: null,
    tableId: null,
    floatLeft: 0,
    floattop: 0,
    floatShow: false,
    currentVos: [],
  }

  componentDidMount() {
    this.getCalendarStatistics() // 获取日历课表信息
    this.getStudyStatistics() //获取学生的学习能量的统计值
    this.fetchIsContainChallenge() // 判断是否包含每日挑战
  }

  // 获取日历课表信息
  getCalendarStatistics = () => {
    http.get('/student/index/calendarStatistics').then(res => {
      const calendarList = res.data
      const [ { month: currMonth, year: currYear }, { month: nextMonth, year: nextYear }] = calendarList
      const currCalendar = this.formatCalendar(calendarList[0])
      const nextCalendar = this.formatCalendar(calendarList[1])
      this.setState({
        currCalendar, nextCalendar, currMonth, currYear, nextMonth, nextYear
      })
    })
  }

  formatCalendar = calendar => {
    const { monthNo, year, vos=[] } = calendar
    // 当前月份的第一天是从星期几开始
    const startDay = new Date(year, monthNo-1, 1).getDay()
    // 当前月份一共有多少天
    const endDate = new Date(year, monthNo, 0).getDate()
    let tempList = []
    let list = []
    for(let i=0; i<startDay+endDate; i++) {
      // console.log('%c startDay+endDate', 'color: red;', startDay+endDate)
      if(i < startDay) {
        tempList.push({ day: 0 })
      }else if(i % 7 === 6) {

        const tempObj = {day: i-startDay+1}
        tempList.push(tempObj)
        const _vos = []
        for(let j=0; j<vos.length; j++) {
          const index = new Date(vos[j].classBeginTime).getDate() + startDay
          if(index == i+1) {
            _vos.push(vos[j])
            tempObj.vos = _vos
            tempObj.isCurrent = _vos[0].isCurrent
          }
        }
        list.push(tempList)
        tempList = []
      }else{
        const tempObj = {day: i-startDay+1}
        tempList.push(tempObj)
        const _vos = []
        for(let j=0; j<vos.length; j++) {
          const index = new Date(vos[j].classBeginTime).getDate() + startDay
          if(index == i+1) {
            _vos.push(vos[j])
            tempObj.vos = _vos
            tempObj.isCurrent = _vos[0].isCurrent
          }
        }
      }
    }
    for(let i=0; i<7; i++) {
      !tempList[i] && tempList.push({ day: 0 })
    }
    list.push(tempList)

    for(let i=0; i<list.length; i++) {
      for(let j=0; j<list[i]; j++) {
        for(let k=0; k<vos.length; k++ ) {
          if(list[i][j].day == new Date(v[k].classBeginTime).getDate()){
            list[i][j] = Object.assign({}, list[i][j], vos[k])
          }
        }
      }
    }
    return list
  }

  renderTables = (calendarData) => {
    return (
      <Fragment>
        <table>
          <thead>
            <tr>
              <th>日</th>
              <th>一</th>
              <th>二</th>
              <th>三</th>
              <th>四</th>
              <th>五</th>
              <th>六</th>
            </tr>
          </thead>
          <tbody>
            {
              calendarData.map((curr, i) => (
                <tr key={i}>
                  {
                    curr.map((cu, j) => (
                      <td 
                        key={`${i}-${j}`} 
                        className={`${cu.isCurrent ? 'current ' : cu.vos ? 'has-class' : ''}`}
                        onMouseMove={cu.vos && this.onMouseMove(cu.vos)}
                        onMouseLeave={this.onMouseLeave}
                      >
                        {cu.day ? cu.day : ''}
                      </td>
                    ))
                  }
                </tr>
              ))
            }
          </tbody>
        </table>
      </Fragment>
    )
  }

  onMouseMove = vos => (e) => {
    this.setState({
      currentVos: vos,
      floatShow: vos && true || false,
      floatLeft: e.target.offsetLeft + 35,
      floatTop: e.target.offsetTop
    })
  }

  onMouseLeave = (e) => {
    this.setState({
      currentVos: [],
      floatShow: false,
      floatLeft: 0,
      floatTop: 0
    })
  }
  
  renderEnergy = () => {
    const {
      englishStudyHours, //累计英语学习时间
      programStudyHours, //累计编程学习时间
      trainTimes, //累计练习次数 
      challengeTimes, //累计挑战次数
    } = this.state
    return (
      <div className="energy-wrap">
        <div className="energy-item">
          <img src={require('../../../images/student/home_icon1.png')} />
          <div>
            <p>累计英语学习时间</p>
            <p>
              <b>{englishStudyHours}</b>
              <span>小时</span>
            </p>
          </div>
        </div>
        <div className="energy-item">
          <img src={require('../../../images/student/home_icon2.png')} />
          <div>
            <p>累计编程学习时间</p>
            <p>
              <b>{programStudyHours}</b>
              <span>小时</span>
            </p>
          </div>
        </div>
        <div className="energy-item">
          <img src={require('../../../images/student/home_icon3.png')} />
          <div>
            <p>累计练习次数</p>
            <p>
              <b>{trainTimes}</b>
              <span>次</span>
            </p>
          </div>
        </div>
        <div className="energy-item">
          <img src={require('../../../images/student/home_icon4.png')} />
          <div>
            <p>累计挑战次数</p>
            <p>
              <b>{challengeTimes}</b>
              <span>次</span>
            </p>
          </div>
        </div>
      </div>
    )
  }

  //获取学生的学习能量的统计值
  getStudyStatistics = () => {
    http.get('/student/index/studyStatistics').then(res => {
      const {
        challengeTimes, //累计挑战次数
        englishStudyHours, //累计英语学习时间
        programStudyHours, //累计编程学习时间
        trainTimes, //累计练习次数
      } = res.data
      this.setState({
        challengeTimes,
        englishStudyHours,
        programStudyHours,
        trainTimes,
      })
    })
  }

  // 判断是否包含每日挑战
  fetchIsContainChallenge = () => {
    http.get('/student/index/isContainChallenge').then(res => {
      const isContainChallenge = res.data
      this.setState({ isContainChallenge })
      // 每日挑战
      if(!isContainChallenge) {
        this.getChallengeVo()
      }
    })
  }

  // 获取首页每日挑战的信息
  getChallengeVo = () => {
    http.get('/student/index/challengeVo').then(res => {
      const { level, tableId } = res.data
      this.setState({ level, tableId })
    })
  }
  // 点击每日挑战的免费试听
  handleFreeAudition = () => {
    this.props.history.push('/student_center/free_classes/layout/free')
  }
  // 前往今日挑战
  handleDailyChallenge = () => {
    const { tableId } = this.state
    const showErrorNotice = true
    http.get('/student/challenge/challengeInfo', { tableId }, undefined, showErrorNotice).then(res => {
      const { id: challengeId } = res.data
      const isPad = getPlatformType()
      if(isPad) {
        this.props.history.push('/#/student_center_/my_courses/layout/daily_challenge_pad/'+challengeId)
      }else {
        window.open('/#/student_center_/my_courses/layout/daily_challenge?challengeId='+challengeId)
      }
    })
  }

  render() {
    const { currCalendar, nextCalendar, isContainChallenge,
      floatShow, floatLeft, floatTop, currentVos=[], currMonth, nextMonth, currYear, nextYear,
    } = this.state
    return (
      <div className="student-center-home">
        <div className="calendar">
          <SubTitle title="课程日历" />
          <div className="float-list" 
            style={{ 
              display: floatShow ? 'block' : 'none', 
              left: floatLeft, 
              top: floatTop,
            }}
          >
            <i style={{display: floatShow ? 'block' : 'none'}}></i>
            <ul>
              {
                currentVos.map(item => {
                  if(item.platform == 3){
                    return <li><p>{item.courseName}</p><span>已解锁本周课程</span></li>
                  }else{
                    return <li><p>{item.courseName}</p><span>{(item.classBeginTime).substr(5,11)}</span></li>
                  }
                })
              }
              {/* <li><p>hahahahah哈哈哈哈哈哈哈哈111111111111</p><span>收快递费思路肯定放假是六块腹肌时空裂缝就是路费就开始九分裤</span></li> */}
            </ul>
          </div>
          <div className="calendar-item-wrap">
            <div>
              <span className="month">{currMonth}</span>
              <span className="year">{currYear}</span>
            </div>
            {
              this.renderTables(currCalendar)
            }
          </div>
          <div className="calendar-item-wrap">
            <div>
              <span className="month">{nextMonth}</span>
              <span className="year">{nextYear}</span>
            </div>
            {
              this.renderTables(nextCalendar)
            }
          </div>
          <div className="home-tip"></div>
        </div>
        <div className="mid-container">
          {/* 学习能量 */}
          <div className="energy-panel">
            <SubTitle title="学习能量" />
            {
              this.renderEnergy()
            }
          </div>
          {/* 每日挑战 */}
          <div className="daily-challenge">
            <SubTitle title="每日挑战" />
            {
              !isContainChallenge ? (
                <div className="challenge-now daily-challenge-item">
                  <p>英语语法闯关大作战</p>
                  <p>挑战等级：<span>Level 01</span></p>
                  <p>挑战规则：<span>每日只允许挑战一次，每次挑战5个关卡， 根据挑战成绩获得战者徽章</span></p>
                  <span onClick={this.handleDailyChallenge}>今日挑战</span>
                  <i className="english-icon"></i>
                </div>
              ) : (
                <div className="free-courses daily-challenge-item">
                  <p>改变世界，从学习开始</p>
                  <span>立即免费试听，加入挑战者联盟</span>
                  <b onClick={this.handleFreeAudition}>免费试听</b>
                </div>
              )
            }
          </div>
        </div>
        {/* 帮助中心 */}
        {/* <div className="help-center-container-pad">
          <HelpCenter theme="dark" />
        </div> */}
      </div>
    )
  }
}